<template>
    <div class="vue-ms-main  vue-ms-main-add" v-loading="loading">
        <div class="ms-top">
            <!-- 当前页标题  -->
            <div class="crumbs fl">
                <el-breadcrumb separator="/">
                    <el-breadcrumb-item><i class="el-icon-menu"></i><a @click="$router.push('/bugList')">  Bug管理</a> </el-breadcrumb-item>
                    <el-breadcrumb-item v-if="paramsId != undefined && paramsId > 0">Bug编辑</el-breadcrumb-item>
                    <el-breadcrumb-item v-if="!(paramsId != undefined && paramsId > 0)">Bug添加</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
        </div>
        <!--  添加 -->
        <div class = "ms-updmain">
            <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <div class="info infos">
                    <div class="fl upd-model" prop="userName">
                        <el-form-item label="bug名称" prop="name" ><i class="xing">*</i>
                            <el-input type="text" v-model="ruleForm.name"  :rules="[{ required: true},]" placeholder="请填写bug名称" auto-complete="on"></el-input>
                        </el-form-item>
                        <el-form-item  label="顶级项目" prop="topProjId"><i class="xing">*</i>
                            <el-select v-model="ruleForm.topProjId" filterable placeholder="请选择" @change="topProjSelect()"><i class="xing">*</i>
                                <el-option v-for="item in topProjList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item  label="次级项目" prop="secondProjId"><i class="xing">*</i>
                            <el-select v-model="ruleForm.secondProjId" filterable placeholder="请选择" @change="secondProSelect()"><i class="xing">*</i>
                                <el-option v-for="item in secondProjList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item  label="三级项目" >
                            <el-select v-model="ruleForm.thirdProjId" filterable placeholder="请选择">
                                <el-option v-for="item in thirdProjList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="bug状态" prop="bugStatus"><i class="xing">*</i>
                            <el-select v-model="ruleForm.bugStatus" filterable placeholder="请选择"><i class="xing">*</i>
                                 <el-option v-for="item in bugStatusList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>

                    </div>
                    <div class="fr upd-model">
                        <el-form-item label="修复人员" ><i class="xing">*</i>
                            <el-select v-model="ruleForm.ownerId" filterable placeholder="请选择"><i class="xing">*</i>
                                <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="测试人员" ><i class="xing">*</i>
                            <el-select v-model="ruleForm.tester" filterable placeholder="请选择">
                                <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="提交人员" ><i class="xing">*</i>
                            <el-select v-model="ruleForm.issuer" filterable placeholder="请选择">
                                <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <!--<el-form-item label="创建时间" prop="start_date"><i class="xing">*</i>-->
                            <!--<el-date-picker v-model="ruleForm.createTime"  align="right" type="datetime"  placeholder="选择日期" :picker-options="pickerOptions1"></el-date-picker>-->
                        <!--</el-form-item>-->
                        <el-form-item label="bug工时" prop="duration" :rules="[{ required: true, message: '请输入项目工时'}]"><i class="xing">*</i>
                            <el-input type="number" v-model="ruleForm.duration"  placeholder="请填写项目工时" auto-complete="on"></el-input>
                        </el-form-item>
                        <el-form-item label="bug等级" prop="bugLevel"><i class="xing">*</i>
                            <el-select v-model="ruleForm.bugLevel" filterable placeholder="请选择"><i class="xing">*</i>
                                <el-option v-for="item in bugLevelList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
                <div class="info infos">
                    <el-form-item label="bug描述" prop="description" ><i class="xing">*</i>
                        <el-input type="textarea" rows="10" v-model="ruleForm.description"  placeholder="请填写项目描述" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
                        <el-button @click="resetForm('ruleForm')">重置</el-button>
                    </el-form-item>
                </div>

            </el-form>
        </div>

    </div>
</template>

<script>
    import insurance from '../../api/insurance';
    export default {
        data() {
            var checkProName = (rule, value, callback) => {if (!value) { return callback(new Error('请输入bug名称'));}else{callback(); }};
            var checkDescription = (rule, value, callback) => {if (!value) { return callback(new Error('请输入项目描述'));}else{callback(); }};
            var checkTopProjId = (rule, value, callback) => {if (!value) { return callback(new Error('请选择顶级项目'));}else{callback(); }};
            var checkSecondProjId = (rule, value, callback) => {if (!value) { return callback(new Error('请选择次级项目'));}else{callback(); }};
            return {
                userList: [],
                paramsId:'',
                paramsRouter:'proAll',
                addStu:true,    // true 为添加  false为修改
                proUpdStu:true, // 修改时 项目进行绑定
                ruleName:{},    //  用来绑定修改时项目名称
                ruleForm: {
                    ID:0,
                    name: undefined,//bug名称
                    description:'',//bug描述
                    topProjId:'',//顶级项目ID
                    secondProjId:'', //次级项目ID
                    thirdProjId:'', //三级项目iD，可选，存在时传
                    ownerId: 32, //研发人员
                    tester:66,//测试人员
                    issuer:parseInt(JSON.parse(sessionStorage.getItem('user')).id),//bug提交人员
                    bugStatus: 2, //bug状态，已对应：0，测试通过：1，新建bug：2，测试未通过：3
                    bugLevel: 3,//bug等级，致命:0,严重：1，一般：2，轻微：3
                    createTime:"",//创建时间，格式待定
                    duration:0,//工时
                    operator:parseInt(JSON.parse(sessionStorage.getItem('user')).id),  //操作员ID
                },
                // 验证
                rules: {
                    name: [ { validator: checkProName, trigger: 'blur' }],
                    description: [ { validator: checkDescription, trigger: 'blur' }],
                    topProjId: [ { validator: checkTopProjId, trigger: 'blur' }],
                    secondProjId: [ { validator: checkSecondProjId, trigger: 'blur' }],

                },
                topProjList:[], //  顶级项目
                secondProjList:[],//  第二级项目
                thirdProjList:[],// 第三级项目
                //  测试状态
                bugStatusList:[{'label':'已对应','value':0},{'label':'测试通过','value':1},{'label':'新建bug','value':2},{'label':'测试未通过','value':3}],
                //bug等级
                bugLevelList:[{'label':'轻微','value':3},{'label':'一般','value':2},{'label':'严重','value':1},{'label':'致命','value':0}],

                loading:false,
                pickerOptions1: {
                    shortcuts: [{
                        text: '今天',
                        onClick(picker) {
                            picker.$emit('pick', new Date());
                        }
                    }, {
                        text: '昨天',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '一周前',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', date);
                        }
                    }]
                },
            };
        },
        watch: {
            '$route': 'getParams'
        },
        methods: {
            submitForm(formName) {
                var that = this;
                var thirdProjId = that.ruleForm.thirdProjId;
                if(thirdProjId === null || thirdProjId === undefined || thirdProjId.length <= 0){
                    thirdProjId = undefined;
                }else{
                    parseInt(thirdProjId)
                }
                if(that.paramsRouter == undefined){
                    that.paramsRouter = 'proAll';
                }
                that.$refs[formName].validate((valid) => {
                    if (valid) {
                        that.addLoading = true;

                        let para = Object.assign({}, that.ruleForm);
                        var createTime = new Date(that.ruleForm.createTime);
                        var ID = undefined;
                        if(!that.addStu){
                            ID = parseInt(para.ID);
                        }


                        var data =JSON.stringify({
                            ID: ID,
                            name: para.name,//bug名称
                            description:para.description,//bug描述
                            topProjId:parseInt(para.topProjId),//顶级项目ID
                            secondProjId: parseInt(para.secondProjId), //次级项目ID
                            thirdProjId:thirdProjId, //三级项目iD，可选，存在时传
                            ownerId: parseInt(para.ownerId), //研发人员
                            tester: parseInt(para.tester),//测试人员
                            issuer:parseInt(para.issuer),//bug提交人员
                            bugStatus:parseInt(para.bugStatus), //bug状态，已对应：0，测试通过：1，新建bug：2，测试未通过：3
                            bugLevel:parseInt(para.bugLevel),//bug等级，致命:0,严重：1，一般：2，轻微：3
                            status:0,
                           // createTime:this.formatData(para.createTime),//创建时间，格式待定
                            duration:para.duration,//工时
                            operator:parseInt(para.operator),  //操作员ID
                            });
                            $.ajax(insurance.posturl+"bug/storgeBug",{
                                'data': data,
                                headers: {'Content-Type': 'application/json;charset=UTF-8'},
                                'type': 'POST',
                                success:function (res) {
                                    res = JSON.parse(res);
                                    if(!res.isSuccess){
                                        that.altopen('添加'+res.msg,'success');
                                    }else{
                                        that.altopen('添加'+res.msg,'success');
                                        that.addFormVisible = false;
                                        that.$router.push({ path: '/bugList' });
                                    }
                                    that.addLoading = false;
                                }
                            });
                            // this.loading = true;
                    } else {
                        this.altopen('请把信息填写完整！','warning');
                        return false;
                    }
                });
            },

            resetForm(formName) {
                // this.$refs[formName].resetFields();
                this.initDay();
            },
            // 公共弹框
            altopen(msg,type) {
                this.$notify({
                    type:type,
                    message: msg,
                    offset: 100,
                });
            },
            // 修改页面传值
            getProList () {
                this.paramsId = this.$route.query.ID;
                this.paramsRouter = this.$route.query.router;
                var that = this;
                var t = new Date;
                this.ruleForm.createTime = new Date(t.getFullYear(), t.getMonth(), t.getDate(), t.getHours(), t.getMinutes());
                var data = {
                    ID: undefined,
                    name: "",//bug名称
                    description: '',//bug描述
                    topProjId: '',//顶级项目ID
                    secondProjId: '', //次级项目ID
                    thirdProjId: '', //三级项目iD，可选，存在时传
                    ownerId: 31, //研发人员
                    tester: 31,//测试人员
                    issuer: 31,//bug提交人员
                    bugStatus: 0, //bug状态，已对应：0，测试通过：1，新建bug：2，测试未通过：3
                    bugLevel: 0,//bug等级，致命:0,严重：1，一般：2，轻微：3
                    duration: 0,//工时
                    operator: 31,  //操作员ID
                };
                if(that.paramsId != undefined && that.paramsId  > 0){
                    that.loading = true;
                    that.addStu = false;
                    that.proUpdStu = false;
                    $.ajax(insurance.posturl+"bug/bugInfo?bugID="+that.paramsId,{
                        headers: {'Content-Type': 'application/json;charset=UTF-8'},
                        'type': 'GET',
                        success:function (res) {
                            res = JSON.parse(JSON.parse(res).Content);
                              data = {
                                  ID: parseInt(res.id),
                                  name: res.name,//bug名称
                                  description:res.description,//bug描述
                                  topProjId:parseInt(res.topProjId),//顶级项目ID
                                  secondProjId:parseInt(res.secondProjId), //次级项目ID
                                  thirdProjId:parseInt(res,thirdProjId), //三级项目iD，可选，存在时传
                                  ownerId:parseInt(res.ownerId), //研发人员
                                  tester:parseInt(res.tester),//测试人员
                                  issuer:parseInt(res.issuer),//bug提交人员
                                  bugStatus:parseInt(res.bugStatus), //bug状态，已对应：0，测试通过：1，新建bug：2，测试未通过：3
                                  bugLevel:parseInt(res.bugLevel),//bug等级，致命:0,严重：1，一般：2，轻微：3
                                  createTime: that.formatData(res.createTime),//创建时间，格式待定
                                  duration: parseInt(res.duration),//工时
                                  operator:JSON.parse(sessionStorage.getItem('user')).id,  //操作员ID
                              };
                              var data2 = {topProjName:res.topProjName,secondProjName:res.secondProjName,thirdProjName:res.thirdProjName};
                              that.ruleName = data2;
                            that.ruleForm = data;
                            that.loading = false;
                        }
                    });
                }
            },

            //获取项目列表
            getProListTop() {
                var that = this;
                $.ajax(insurance.posturl+"proj/allProjs?page=0&pageSize=10000&usrID="+JSON.parse(sessionStorage.getItem('user')).id+'&mode=1',{
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'GET',
                    success:function (res) {
                        res = JSON.parse(JSON.parse(res).Content);
                        that.totalRecord = res.count;
                        var data = [];
                        for(var i = 0; i<res.list.length; i++){
                            var d = {'label':res.list[i].projectName,'value':parseInt(res.list[i].ID)};
                            data.push(d);
                        }
                        that.topProjList = data;
                    }
                });
            },
            //  第一级选择
            topProjSelect(){
                this.ruleForm.secondProjId = '';
                this.ruleForm.thirdProjId = '';
                this.getProInfo(this.ruleForm.topProjId,2)
            },
            //  第二级选择
            secondProSelect(){
                this.ruleForm.thirdProjId = '';
                this.getProInfo(this.ruleForm.topProjId,3)
            },

            // 详情获取
            getProInfo(id,type){
                var that = this;
                $.ajax(insurance.posturl+"proj/projInfo?projID="+id,{
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'GET',
                    success:function (res) {
                        res = JSON.parse(JSON.parse(res).Content);
                        var data = [];
                        var types = '1';
                        if(type == 3){ types = '2'; }
                        for(var i = 0; i<res.length; i++){
                            if(res[i].type == types){
                                var d = {'label':res[i].projectName,'value':parseInt(res[i].ID)};
                                data.push(d);
                            }
                        }
                        (type == 2)? that.secondProjList = data:that.thirdProjList = data;
                    }
                });
                this.getUser();
                gantt.serverList("staff", JSON.parse(window.localStorage.getItem('userList2')));
            },

            // 用户列表
            getUser(){
                var that = this;
                $.ajax(insurance.posturl+"user/AllUsers?page=0&pageSize=200",{
                    headers: {'Content-Type': 'application/json;charset=UTF-8'},
                    'type': 'GET',
                    success:function (res) {
                        res = JSON.parse(JSON.parse(res).Content);
                        var datas = [];
                        for(var i = 0; i<res.list.length; i++){
                            datas.push({'value':parseInt(res.list[i].id),'label':res.list[i].name});
                        }
                        that.userList = datas;
                    }
                });
            },
            // 日 - 月
            dateR(d){
                var dates = d.split('-');
                return dates[1] + '-' + dates[0] + '-' + dates[2];
            },
            formatData(d){
                var d1 = new Date();
                if(d != undefined){
                    d1 = new Date(d);
                }
                var m = d1.getMonth()+1;
                var d = d1.getDate();
                if((m+'').length <= 1){
                    m = '0'+m;
                }
                if((d+'').length <= 1){
                    d = '0'+d1.getDate();
                }
            },
            // 初始化数据
            initDay(){
                this.getProListTop();  // 第一级项目列表
                var t = new Date;
                this.ruleForm.createTime = new Date(t.getFullYear(), t.getMonth(), t.getDate(), t.getHours(), t.getMinutes());
                this.getUser(); //  用户列表
                this.getProList();// 修改页面接受值
            },
        },
        mounted(){
            this.initDay();
        }
    }
</script>
<style>
    .el-form-item__content{position: relative};

    .xing{color: red; font-size: 20px; position: absolute;left: -75px; top: 7px;}
    .img-upd-div{height: 134px; width: 225px; float:left; overflow: hidden;border: #ccc 1px solid;margin-bottom: 5px; margin-right: 5px; position: relative}
    .img-upd-div .el-form-item__error{ position: absolute; bottom: 0px;  text-align: center; left: 0px; width: 100%;}
    .image-list2 .img-uplod{
        position: absolute;
        z-index: 999;
        background: transparent;
        top: -24px;
        width: 100%;
        height: 160px !important;
        color: #fff;
    }
    .el-form-item.is-required .el-form-item__label:before{display: none;}

</style>
